package com.zufangbao.earth.task;

import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.zufangbao.earth.handler.BillDepositeHandler;
import com.zufangbao.earth.service.AppParticlesService;
import com.zufangbao.earth.service.AuthorisedBillSketchService;
import com.zufangbao.earth.service.ParticalService;
import com.zufangbao.gluon.api.quark.AuthorisedBillSketch;
import com.zufangbao.gluon.exception.CommonException;
import com.zufangbao.sun.entity.company.corp.App;
import com.zufangbao.sun.service.AppService;

@Component
public class SyncBillTask {

	@Autowired
	private BillDepositeHandler billDepositeHandler;
	
	@Autowired
	private AuthorisedBillSketchService authorisedBillSketchService;
	
	@Autowired
	private AppService appService;
	
	@Autowired
	private ParticalService particalService;
	
	@Autowired
	private AppParticlesService appParticleService;
	
	private static Log logger = LogFactory.getLog(SyncBillTask.class);
	
	/**
	 * 每天0点同步订单数据
	 */
	@Scheduled(cron = "0 0 0 * * ?")
	public void syncBill(){
		
		logger.info("begint to sync bill from quark");
		 
			try {
				List<App> apps = appService.loadAll(App.class);
				 
				 for(App app : apps){
					 
					 List<String> particalUniqueIds = appParticleService.getQuarkParticalUniqueIds(app.getAppId());
					 
					 if(CollectionUtils.isEmpty(particalUniqueIds)){
						 
						 continue;
					 }
					 
					 for(String particalUniqueId : particalUniqueIds){
						 
						List<AuthorisedBillSketch> hotBillSketchs = null;
						
						try {
							
							hotBillSketchs = billDepositeHandler.pullHotBillByApp(app);
							
						} catch (CommonException e) {
							
							logger.error("pull hot bills by app error code["+e.getErrorCode()+"]");
						}
						 if(CollectionUtils.isEmpty(hotBillSketchs)){
							 
							 logger.info("hot bill sketchs is empty");
							 
							 continue;
						 }
						 
						 List<String> uniqueBillIds = null;
						 
						try {
							
							uniqueBillIds = authorisedBillSketchService.updateOrderByHotBillSketchs(hotBillSketchs);
							
						} catch (CommonException e) {
							
							logger.error("update local data error["+e.getErrorCode()+"]");
						}
						 
						try {
							
							billDepositeHandler.coolingHotBills(uniqueBillIds, particalUniqueId);
							
						} catch (CommonException e) {
						
							logger.error("cooling hot bills error["+e.getErrorCode()+"]");
						}
					 }
				 }
			} catch (Exception e) {
				
				logger.error("sync bill error["+e.getMessage()+"]");
			}
			 logger.info("end to sync bill from quark");
	 }
}
